import {ElMessage, ElLoading } from 'element-plus'
import service from '@/utils/request'  
import { saveAs } from 'file-saver'
import {blobValidate} from '@/utils/ruoyi'  

const errorCode = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    'default': '系统未知错误，请反馈给管理员'
  }

 // 获取文件名称
 export const getDownFileName= function (name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (!name) {
    return '';
  }
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

export const downloadFile=(url, params, filename) =>{  
    let downloadLoadingInstance = ElLoading.service({ text: "Downloading Data,Please Waiting", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", }) 
    return service.post(url, params,
        {
       transformRequest: [(params) => { return JSON.stringify(params) }],
       headers: { 'Content-Type': 'application/json' },
       responseType: 'blob',
       timeout:30000,
    }).then(async(data)=>{ 
        const isBlob = blobValidate(data);
        if (isBlob) {
        const blob = new Blob([data])
        saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || rspObj.message|| errorCode['default']
            ElMessage.error(errMsg);
        }
    downloadLoadingInstance.close();
    }).catch((r) => {
      console.log(r)
      //ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close();
    })
  }
 